<?php
namespace xcom\model;
use x\Xbase;
class Userbill extends Xbase
{
    /**
     * 创建账单， 变动用户资金
     */
    public function doit($order_no, $user_id, $type,$table, $table_id,$money,$money_type='money',$note='',$fee=0,$v_num=0){

        if( $money<=0){
            $this->setError('资金错误!');
            return false;
        }
        $user = $this->db->find('user',$user_id,"$money_type,id,v");
        if ( !$user ){
            $this->setError('用户错误!');
            return false;
        }

        $d = [
            'type'              => $type,
            'tab'               => $table,
            'tab_id'            => $table_id,
            'order_no'          => $order_no,
            'money_type'        => $money_type,

            'user_id'           => $user_id,
            'note'              => $note,
            'before_money'      => $user[$money_type],
            'money'             => $money,

            'after_money'       => $user[$money_type],
            'fee'               => $fee,
            'create_time'       => time(),

        ];
       #加
        if($type>=100 && $type<200){
            $d['after_money']  = bcadd($d["before_money"], $money, 2);
            $d['show_money']   = "+".bcadd($money,0,2);
        #减
        }else if($type>=200){
            $d['after_money']  = bcsub($d["before_money"], $money, 2);
            $d['show_money']   = "-".bcadd($money,0,2);
        }

        if($d['after_money']<0){
            $this->setError('余额不足!');
            return false;
        }
       #更新用户
       $v = $user['v']+1;
       $data = [
           'id'=>$user['id'],
           'v'=>$v,
           $money_type=>$d['after_money'],
       ];
       $result = $this->db->update('user',$data,['id=? and v=?',[$user['id'],$user['v']]]);
       if(!$result){
           if($v_num<2){
               #重新执行一次
               sleep(1);
               $v_num = $v_num+1;
               return $this->doit($order_no,$user_id,$type,$table,$table_id,$money,$note,$fee,$v_num);
           }
           $this->setError('更新用户资金失败');
           return false;
       }
       $id = $this->db->insert('user_bill', $d);
        if( !$id ){
            $this->setError('创建账单失败');
            return false;
        }else{
            return $id;
        }
    }
}
